package com.biubiushop.service.impl;

import cn.hutool.core.date.DateUtil;
import com.biubiushop.entity.Equipment;
import com.biubiushop.repository.IEquipmentRepository;
import com.biubiushop.service.IEquipmentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EquipmentServiceImpl implements IEquipmentService {

    @Resource
    IEquipmentRepository equipmentRepository;

    /**
     * 地球半径,单位 m
     */
    private static final double EARTH_RADIUS = 6378137;

    @Override
    public Boolean addEquipment(Integer type, String agentId, Double longitude,
                                Double latitude,String address, Boolean isUse, Boolean isNormal, Integer overLength) throws Exception {
        Equipment equipment = new Equipment();
        equipment.setType(type);
        //equipment.setAgentId(agentId);
        equipment.setLongitude(longitude);
        equipment.setLatitude(latitude);
        equipment.setAddress(address);
        equipment.setIsUse(isUse != null);
        equipment.setIsNormal(isNormal != null);
        equipment.setCreateTime(DateUtil.parse(DateUtil.now(), "yyyy-MM-dd HH:mm:ss"));
        equipment.setOverLength(overLength);
        equipmentRepository.save(equipment);
        return true;
    }

    @Override
    public List<Object> getNearEquipment(Double longitude,Double latitude) throws Exception{
        //获取所有设备信息
        List<Equipment> equipmentList = equipmentRepository.findAll();
        Double targetLongitude;
        Double targetLatitude;
        long distance;
        for (Equipment equitpment:equipmentList
             ) {
            //目标点经度
            targetLongitude = equitpment.getLongitude();
            targetLatitude = equitpment.getLatitude();
            distance = getDistance(longitude,latitude,targetLongitude,targetLatitude);

        }




        return null;
    }

    /**
     * 根据经纬度，计算两点间的距离
     *
     * @param longitude1 第一个点的经度
     * @param latitude1  第一个点的纬度
     * @param longitude2 第二个点的经度
     * @param latitude2  第二个点的纬度
     * @return 返回距离 单位千米
     */
    private static long getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        // 纬度
        double lat1 = Math.toRadians(latitude1);
        double lat2 = Math.toRadians(latitude2);
        // 经度
        double lng1 = Math.toRadians(longitude1);
        double lng2 = Math.toRadians(longitude2);
        // 纬度之差
        double a = lat1 - lat2;
        // 经度之差
        double b = lng1 - lng2;
        // 计算两点距离的公式
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2)));
        // 弧长乘地球半径, 返回单位: 千米
        return Math.round(s * EARTH_RADIUS);
    }

    public static void main(String[] args) {
        long d = getDistance(116.308479, 39.983171, 116.353454, 49.996059);
        System.out.println(d);
    }
}
